package com.specter.serv.controller;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.specter.serv.service.UserOauthService;
import com.specter.utils.StringUtils;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 三方接入认证（支持 微信/钉钉/政务钉）
 * 
 * @author Liang.Wang
 * @since 2025-04-01 09:05:01
 */
@Controller
@RequestMapping("/sure/oauth")
public class OAuth2ServController {

	@Autowired
	private UserOauthService oAuthService;

	/**
	 * 内置登录小页面
	 */
	@RequestMapping("/access")
	public ModelAndView access(Model model) {
		return new ModelAndView("access");
	}

	/**
	 * 登录提交方法
	 */
	@RequestMapping(value = "/authorize")
	public Object authorize(Model model, HttpServletRequest request) {
		try {
			// 检查传入的客户端id是否正确
			if (!oAuthService.validateClientId(request.getParameter("client_id"))) {
				return new ResponseEntity<String>("{\"error\":\"invalid_client\"}", HttpStatus.BAD_REQUEST);
			}

			// responseType目前仅支持CODE，另外还有TOKEN
			String responseType = request.getParameter("response_type");
			String redirectURI = request.getParameter("redirect_uri");// 得到到客户端重定向地址

			// 如果用户没有登录，跳转到登陆页面
			if (!login(request)) {
				// 登录失败时跳转到登陆页面
				model.addAttribute("response_type", responseType);
				model.addAttribute("redirect_uri", redirectURI);
				model.addAttribute("client", new Object());
				return "oauth2login";
			}

			String username = request.getParameter("username"); // 获取用户名

			// 生成授权码
			String authorizationCode = null;
			if (responseType.equals("code")) {
				authorizationCode = UUID.randomUUID().toString();
				oAuthService.addAuthCode(authorizationCode, username);
			}

			// 进行OAuth响应构建
			redirectURI += redirectURI.contains("?") ? "?" : "&" + "&state=" + request.getParameter("state") + "&code=" + authorizationCode;
			// 根据OAuthResponse返回ResponseEntity响应
			HttpHeaders headers = new HttpHeaders();
			headers.setLocation(new URI(redirectURI));
			return new ResponseEntity<HttpHeaders>(headers, HttpStatus.FOUND);
		} catch (Exception e) {

			// 出错处理
			String redirectUri = e.getMessage().contains("http://") ? e.getMessage() : null;
			if (StringUtils.isEmpty(redirectUri)) {
				// 告诉客户端没有传入redirectUri直接报错
				HttpHeaders responseHeaders = new HttpHeaders();
				responseHeaders.add("Content-Type", "application/json; charset=utf-8");

				return new ResponseEntity<String>("", responseHeaders, HttpStatus.NOT_FOUND);
			}
			// 返回错误消息（如?error=）
			redirectUri += redirectUri.contains("?") ? "?" : "&" + "&error=" + e.getMessage();
			HttpHeaders headers = new HttpHeaders();
			try {
				headers.setLocation(new URI(redirectUri));
			} catch (URISyntaxException e1) {
				e1.printStackTrace();
			}
			return new ResponseEntity<HttpHeaders>(headers, HttpStatus.FOUND);
		}
	}

	private boolean login(HttpServletRequest request) {
		if (request.getMethod().equals("GET")) {
			request.setAttribute("error", "非法的请求");
			return false;
		}

		String username = request.getParameter("username");
		String password = request.getParameter("password");
		if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
			request.setAttribute("error", "登录失败:用户名或密码不能为空");
			return false;
		}

		try {
			// 写登录逻辑
			Object user = request.getAttribute("user");
			if (user != null) {
				if (username.equals(password) ) {
					request.setAttribute("error", "登录失败:密码不正确");
					return false;
				} else {
					return true;
				}
			} else {
				request.setAttribute("error", "登录失败:用户名不正确");
				return false;
			}
		} catch (Exception e) {
			request.setAttribute("error", "登录失败:" + e.getClass().getName());
			return false;
		}
	}

}
